<?php

namespace App\Traits;

use App\Models\Image;

trait HasImages
{
    public static function bootHasImages(): void
    {
        static::saved(
            function ($model) {
                $model->images()->delete();

                $creates = [];

                $images = \request()->input('images') ?? [];
                foreach ($images as $image) {
                    $creates[] = new Image(['url' => $image['url'], 'type' => $image['type'] ?? null]);
                }
                $model->images()->saveMany($creates);
            }
        );

        static::deleted(
            function ($model) {
                $model->images()->delete();
            }
        );
    }

    public function images()
    {
        return $this->morphMany(Image::class, 'imageable');
    }
}
